#include "linphonecore.h"

#include <linphone/messenger_err.h>
#define CONFIG_FILE  "cfg.txt"

typedef struct _Messenger{
	LinphoneCore *linphone;
	int          errcode;
}Messenger;

Messenger m = {NULL,MESSENGER_SUCCESS};

int messenger_get_last_err(){
	return m.errcode;
}

int messenger_create(const LinphoneCoreVTable *vtable){
	
	if(m.linphone != NULL){
		return -1;
	}
	
	m.linphone = linphone_core_new (vtable, CONFIG_FILE, NULL, NULL);
	if(m.linphone == NULL){
		return -1;
	}
	return 0;
}

void messenger_destory(){
	if(m.linphone != NULL){
		linphone_core_destroy (m.linphone);
		m.linphone = NULL;
	}
}

void messener_iterator(){
	if(m.linphone != NULL){
		linphone_core_iterate(m.linphone);
	}
}

int messener_login(const char *username, const char *userid,
				   const char *passwd, const char *ha1,const char *realm){
	LinphoneProxyConfig *cfg = NULL;
	LinphoneAuthInfo *pending_auth = NULL;

	if(linphone_core_get_default_proxy(m.linphone,&cfg) == -1){
		return MESSENGER_NOPROXY;
	}

	pending_auth = linphone_auth_info_new(username,userid,passwd,ha1,realm);

	linphone_core_add_auth_info(m.linphone,pending_auth);

	linphone_proxy_config_enable_register(cfg,TRUE);
	linphone_proxy_config_done(cfg);

	return MESSENGER_SUCCESS;
}

void messenger_logout(){
	LinphoneProxyConfig *cfg = NULL;
	SipSetupContext *ssctx = NULL;

	if(m.linphone == NULL){
		return;
	}

	if(linphone_core_get_default_proxy(m.linphone,&cfg) == -1){
		return;
	}

	linphone_proxy_config_enable_register(cfg,FALSE);
	linphone_proxy_config_done(cfg);
}

LinphoneChatRoom * messenger_create_chatroom(char *uri,void *userdata){
	LinphoneChatRoom *cr = NULL;

	if(m.linphone != NULL){
		return NULL;
	}
	cr = linphone_core_create_chat_room(m.linphone,uri);
	linphone_chat_room_set_user_data(cr,userdata);
	return cr;
}

void messenger_dstroy_charroom(LinphoneChatRoom *cr){
	if(!m.linphone || !cr){
		return;
	}
	linphone_chat_room_destroy(cr);
}

void messenger_send_message(LinphoneChatRoom *cr,char *msg){
	if(!m.linphone || !cr){
		return;
	}
	linphone_chat_room_send_message(cr,msg);
}

void messenger_set_online_status(int minutes_away,const char *contact,LinphoneOnlineStatus presence_mode){
	if(!m.linphone){
		return;
	}

	linphone_core_set_presence_info(m.linphone,minutes_away,contact,presence_mode);
}

//void messenger_add_friend(const char *name, const char *addr){
//
//}
//
//int messenger_friend_delete(int num){
//
//}